package com.example.xiaoshuo_yudu.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.xiaoshuo_yudu.config.PasswordConfig;
import com.example.xiaoshuo_yudu.entity.dto.AdminUsersAddDTO;
import com.example.xiaoshuo_yudu.entity.dto.AdminUsersUpdateDTO;
import com.example.xiaoshuo_yudu.entity.entity.Users;
import com.example.xiaoshuo_yudu.mapper.AdminMapper;
import com.example.xiaoshuo_yudu.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 作者:xuSen
 * 日期2025/7/26 15:42
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Users> implements AdminService {
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private UsersServiceImpl usersServiceimpl;
    @Autowired
    private PasswordConfig passwordConfig;

    /**
     * 添加用户
     * @param user
     */
    @Override
    public void addUser(AdminUsersAddDTO user) {
        Users users = new Users();
        if(usersServiceimpl.existsAccountByUsername(user.getUsername()))
            throw new RuntimeException("用户名已存在");
        users.setUsername(user.getUsername());
        if(usersServiceimpl.existsAccountByEmail(user.getEmail()))
            throw new RuntimeException("邮箱已存在");
        users.setEmail(user.getEmail());
        String password = passwordConfig.passwordEncoder().encode(user.getPassword());
        users.setPasswordHash(password);
        users.setAvatarUrl(user.getAvatarUrl());
        users.setRole(user.getRole());
        // 使用传入的userStatus，如果为空则默认为1（正常）
        users.setUserStatus(user.getUserStatus() != null ? user.getUserStatus() : 1);
        users.setCreateTime(LocalDateTime.now());
        this.save(users);
    }

    /**
     * 删除用户
     * @param userid
     */
    @Override
    public void deleteUser(Integer userid) {
        boolean b = this.removeById(userid);
        if(!b)
            throw new RuntimeException("删除失败");
    }

    /**
     * 更新用户
     * @param user
     */
    @Override
    public void updateUser(AdminUsersUpdateDTO user) {
        Users users = new Users();
        users.setUserId(user.getUserId());
        users.setUsername(user.getUsername());
        users.setEmail(user.getEmail());
        users.setAvatarUrl(user.getAvatarUrl());
        users.setRole(user.getRole());
        users.setUserStatus(user.getUserStatus());
        users.setCreateTime(user.getCreateTime());
        boolean b = this.updateById(users);
        if(!b)
            throw new RuntimeException("更新失败");
    }

    /**
     * 切换用户状态（禁用/启用）
     * @param userId 用户ID
     * @param status 目标状态（0=禁用，1=启用）
     */
    @Override
    public void toggleUserStatus(Integer userId, Integer status) {
        Users users = new Users();
        users.setUserId(userId);
        users.setUserStatus(status);
        boolean b = this.updateById(users);
        if (!b)
            throw new RuntimeException("更新用户状态失败");
    }

    /**
     * 获取用户分页
     *
     * @param keyword
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public List<Users> getUserPage(String keyword, Integer pageNum, Integer pageSize) {
        // 计算偏移量
        int offset = (pageNum - 1) * pageSize;
        List<Users> users = adminMapper.getUserPage(keyword, pageSize, offset);
        return users;
    }

    @Override
    public int getUserCount(String keyword) {
        int count = adminMapper.count(keyword);
        return count;
    }
}